import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import dataPreferences from '@ohos.data.preferences';
const permissions: Array<Permissions> = ['ohos.permission.DISTRIBUTED_DATASYNC',"ohos.permission.READ_MEDIA"];
import {initDatabase} from "../common/util"
import web_webview from '@ohos.web.webview';
import ExpenseStore from "../common/ExpenseStore"
import AlbumStore from "../common/AlbumStore"
export default class EntryAbility extends UIAbility {

  onCreate(want, launchParam) {
    //初始化分布式KV数据库,经过尝试，发现只有以这种方式初始化才不会出现问题
    globalThis.expenseStore=new ExpenseStore(this.context)
    globalThis.albumStore=new AlbumStore(this.context)
    web_webview.WebviewController.initializeWebEngine()
    let promise=dataPreferences.getPreferences(this.context,"myStore")
    promise.then((pre)=>{
      pre.has("isInitData").then((isInit)=>{
        if(!isInit){
          initDatabase(this.context,()=>{
            pre.put("isInitData",1).then(()=>{
              console.debug("数据初始化成功")
              pre.flush()
            })
          })
        }

      })
    })
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
    globalThis.expenseStore.close()
    globalThis.albumStore.close()
  }

  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    let atManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗

    atManager.requestPermissionsFromUser(this.context, permissions).then((data) => {
      let grantStatus: Array<number> = data.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] === 0) {
          // 用户授权，可以继续访问目标操作
        } else {
          // 用户拒绝授权，提示用户必须授权才能访问当前页面的功能，并引导用户到系统设置中打开相应的权限
          return;
        }
      }
      // 授权成功
    }).catch((err) => {
      console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
    })

    windowStage.loadContent('pages/Splash', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });

  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
